package com.microservice.consumer.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 使用 @EnableDiscoveryClient 注解
 * 先通过 discoveryClient 来通过 Ribbon 获取所有的实例，然后自己决定用哪个实例上的服务，自己做负载均衡。没有利用Ribbon的负载均衡
 * 一般在需要获取所有实例时，才用这种方式
 */

@RestController
@RequestMapping("/discovery")
public class DiscoveryController {

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/trigger/{producer}")
    public String discovery(@PathVariable String producer) {
        RestTemplate restTemplate = new RestTemplate();
        List<ServiceInstance> instances = discoveryClient.getInstances(producer);   // 获取所有这个服务的实例
        if (instances.size() == 0) {
            return "No much instance, please check service ID";
        }

        // 自己决定用哪个机器，自己来做负载均衡
        String serviceUri = String.format("%s/produce/data/test-data", instances.get(0).getUri().toString());

        System.out.println("=======Uri===== " + serviceUri);
        ResponseEntity<String> data = restTemplate.exchange(serviceUri, HttpMethod.GET, null, String.class);
        return data.getBody();
    }
}
